<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MRIOResult-leaflet</title>
  <link rel="stylesheet" th:href="@{/leaflet/leaflet.css}" />
  <link rel="stylesheet" th:href="@{/layui/css/layui.css}" />
  <script th:src="@{/leaflet/leaflet.js}" type="text/javascript"></script>
  <script th:src="@{/leaflet/leaflet.curve.js}" type="text/javascript"></script>
  <script th:src="@{/leaflet/leaflet.ChineseTmsProviders.js}" type="text/javascript"></script>
  <script th:src="@{/leaflet/leaflet.mapCorrection.min.js}" type="text/javascript"></script>
  <script th:src="@{/leaflet/arrowHeader/leaflet-geometryutil.js}" type="text/javascript"></script>
  <script th:src="@{/leaflet/arrowHeader/leaflet-arrowheads.js}" type="text/javascript"></script>
  <script th:src="@{/js/jquery-3.1.1.js}" type="text/javascript"></script>
  <script th:src="@{/layui/layui.js}" type="text/javascript"></script>
  <style>
    html,body{
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    #map{
      width: 100%;
      height: 100%;
    }
    .province{
      width: 300px;
      z-index: 999;
      text-align: right;
      position: absolute;
      bottom: 10px;
      right: 10px;
    }
    .legend{
      z-index: 999;
      position: absolute;
      bottom: 10px;
      left: 10px;
      color: #fff;
      width: 150px;
    }
    .legendLine{
      width: 50px;
      margin-top: 5px ;
    }
    .legendLine .layui-row{
      height: 35px !important;
      line-height: 30px !important;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <div class="legend">

  </div>

  <div class="province">
    <form class="layui-form" action="">
      <div class="layui-form-item" style="color: #fff">
        <label class="layui-form-label">数据流方向</label>
        <div class="layui-input-block">
          <input lay-filter="type" type="radio" name="type" value="export" title="输出" checked="">
          <input lay-filter="type" type="radio" name="type" value="import" title="输入">
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Beijing" name="Beijing" title="Beijing" checked="">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Tianjin" name="Tianjin" title="Tianjin">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Hebei" name="Hebei" title="Hebei">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Shanxi" name="Shanxi" title="Shanxi">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="InnrMongolia" name="InnrMongolia" title="InnrMongolia">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Liaoning" name="Liaoning" title="Liaoning">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Jilin" name="Jilin" title="Jilin">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Heilongjiang" name="Heilongjiang" title="Heilongjiang">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Shanghai" name="Shanghai" title="Shanghai">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Jiangsu" name="Jiangsu" title="Jiangsu">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Zhejiang" name="Zhejiang" title="Zhejiang">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Anhui" name="Anhui" title="Anhui">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Fujian" name="Fujian" title="Fujian">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Jiangxi" name="Jiangxi" title="Jiangxi">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Shandong" name="Shandong" title="Shandong">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Henan" name="Henan" title="Henan">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Hubei" name="Hubei" title="Hubei">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Hunan" name="Hunan" title="Hunan">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Guangdong" name="Guangdong" title="Guangdong">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Guangxi" name="Guangxi" title="Guangxi">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Hainan" name="Hainan" title="Hainan">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Chongqing" name="Chongqing" title="Chongqing">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Sichuan" name="Sichuan" title="Sichuan">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Guizhou" name="Guizhou" title="Guizhou">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Yunnan" name="Yunnan" title="Yunnan">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Tibet" name="Tibet" title="Tibet">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Shaanxi" name="Shaanxi" title="Shaanxi">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Gansu" name="Gansu" title="Gansu">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Qinghai" name="Qinghai" title="Qinghai">
          </div>
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Ningxia" name="Ningxia" title="Ningxia">
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-xs6">
            <input lay-filter="province" type="checkbox" value="Xinjiang" name="Xinjiang" title="Xinjiang">
          </div>
        </div>
      </div>
    </form>
  </div>
  <script type="text/javascript">
    let coordinates = {};
    let provinceList = [];
    let activeProvince = ["Beijing"];
    let datas = [];
    let colors = [];
    let maxValue=-1, minValue=-1;
    let type = "export";
    let markerLayer = null;
    let lineLayer = null;
    let map;
    let init = true;
    let legends = [];

    function byte2Hex(n)
    {
      var nybHexString = "0123456789ABCDEF";
      return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
    }

    function RGB2Color(r,g,b)
    {
      return '#' + byte2Hex(r) + byte2Hex(g) + byte2Hex(b);
    }

    function setColors(len,phase)
    {
      if (phase == undefined) phase = 0;
      let center = 128;
      let width = 127;
      let legendHtml = "";

      let frequency = Math.PI*2/len;
      for (let i = 0; i < len; ++i)
      {
        let red   = Math.sin(frequency*i+2+phase) * width + center;
        let green = Math.sin(frequency*i+0+phase) * width + center;
        let blue  = Math.sin(frequency*i+4+phase) * width + center;
        colors.push(RGB2Color(red,green,blue));
      }
    }

    function drawLegend(){
      let legendHtml = "";
      legends.forEach(function (item, i){
        legendHtml += "<div class=\"layui-row\"><div class=\"layui-col-xs5\"><div class='legendLine' style='height:" + (i+1) + "px;background-color: " + item.color + "'></div></div>"
        legendHtml += "<div class=\"layui-col-xs7\">" + item.text + "</div></div>"
      });

      $(".legend").html(legendHtml);
    }

    function getCoordinate(){
      $.get("/province/getAll", function (result){
        coordinates = {};
        if (result?.length > 0){
          provinceList = result;
          for(let i in result){
            let item = result[i];
            if (item?.province){
              coordinates[item.province] = [item.latitude, item.longitude];
              let marker = L.circleMarker([item.latitude, item.longitude], {radius:5});
              let label = L.marker([item.latitude, item.longitude], {
                icon: L.divIcon({
                  className: "labelClass",
                  html: "<div style='width:50px;text-align: center;color:#fff'>" + item.province + "</div>",
                  iconAnchor: [-2, 7]
                })
              });
              markerLayer.addLayer(marker);
              markerLayer.addLayer(label);
            }
          }

          if (init){
            getData();
            init = false;
          }
        }
      });
    }

    function getData(){
      let url = "";
      if (type == "export") {
        url = "/resultExport/findByProvinceExportListAndItem";
      }else{
        url = "/resultExport/findByProvinceImportListAndItem";
      }
      $.post(url, {
        "provinces": activeProvince,
        "itemName": "NO2_Air"
      }, function (result) {
        datas = [];
        if (result?.length > 0) {
          result.sort(function (a, b) {
            return a.value - b.value
          });
          result.forEach(function(item, i){
            if (item.value > 0){
              datas.push(item);
            }
          });
          minValue = datas[0].value;
          maxValue = datas[datas.length - 1].value;
          // $(".min").html(minValue);
          // $(".max").html(maxValue);
          colors = [];
          legends = [];

          if (datas.length <= 5){
            setColors(datas.length);
            datas.forEach(function (item, i) {
              item.color = colors[i];
              item.lineWidth = i+1;
              legends.push({color:colors[i], width:i+1, text:item.value});
            });
          }else{
            setColors(5);
            let i = 1;
            let offset = (maxValue-minValue)/5.0;
            datas.forEach(function (item, j){
              let temp = minValue + i * offset;
              if (item.value == maxValue){
                item.color = colors[4];
                item.lineWidth = 5;
              }else {
                if (item.value < temp) {
                  item.color = colors[i - 1];
                  item.lineWidth = i;
                  console.log(item.value, i);
                } else {
                  i++;
                  temp = minValue + i * offset;
                  while (item.value >= temp) {
                    i++;
                    temp = minValue + i * offset;
                  }
                  item.color = colors[i - 1];
                  item.lineWidth = i;
                  console.log(item.value, i);
                }
              }
            });
            // datas.forEach(function (item, i){
            //   let index = Math.ceil((item.value-minValue) * (5.0/(maxValue - minValue)));
            //
            //   item.color = colors[index];
            //   item.lineWidth = index+1;
            // });
            for (let i =0; i<5; i++){
              let label = (minValue + i*(maxValue-minValue)/5.0) + " - " + (minValue + (i+1)*(maxValue-minValue)/5.0);
              legends.push({color:colors[i], width:i, text: label});
            }
          }

          drawLine();
          drawLegend();
        }
      });
    }

    function drawLine(){
      lineLayer.clearLayers();
      datas.forEach(function(item, i){
        let fromCoords = coordinates[item.provinceExport];
        let toCoords = coordinates[item.provinceImport];
        if (fromCoords && toCoords){
          let midpointLatLng = getMidPoint(fromCoords, toCoords);
          let path =  L.curve(['M', fromCoords, 'Q', midpointLatLng, toCoords], {color: item.color, weight:item.lineWidth});
          lineLayer.addLayer(path);
          let arrow = L.polyline([ midpointLatLng, toCoords ], {opacity:0}).arrowheads({ yawn: 40, color: item.color, fill:true, size: '10px', opacity:1 });
          lineLayer.addLayer(arrow);
          path.bindTooltip(item.provinceExport + " --> " + item.provinceImport + ": " + item.value);
        }
      })
    }

    function getMidPoint(fromCoords, toCoords){
      let offsetX = toCoords[1] - fromCoords[1];
      let offsetY = toCoords[0] - fromCoords[0];
      let r = Math.sqrt( Math.pow(offsetX, 2) + Math.pow(offsetY, 2) );
      let theta = Math.atan2(offsetY, offsetX);
      let thetaOffset = (3.14/10);
      let r2 = (r/2)/(Math.cos(thetaOffset));
      let theta2 = theta + thetaOffset;
      let midpointX = (r2 * Math.cos(theta2)) + fromCoords[1];
      let midpointY = (r2 * Math.sin(theta2)) + fromCoords[0];
      return [midpointY, midpointX];
    }

    layui.use(['form', 'layer', 'jquery' ], function () {
      let form = layui.form,
              layer = layui.layer;
      form.on('radio(type)', function (data){
        type = data.value;
        getData();
      });
      form.on('checkbox(province)', function (data) {
        let checked = data.elem.checked;
        if (checked){
          activeProvince.push(data.value);
        }else if (activeProvince.length > 1){
          for (let i=0; i<activeProvince.length; i++){
            if (activeProvince[i] === data.value){
              activeProvince.splice(i, 1);
            }
          }
        }else{
          $("input[name='" + data.value + "']").prop("checked", true);
          form.render();
          layer.msg('最少选中一个城市！');
        }

        getData();
      });
    });

    $(function(){
      map = L.map('map', {
        zoomControl: false,
        attributionControl: false,
        crs: L.CRS.EPSG3857
      }).setView([33.835673,105.403835], 4);

      let geoqPurplishBlue = L.tileLayer.chinaProvider('Geoq.Normal.PurplishBlue').addTo(map);
      markerLayer = new L.FeatureGroup().addTo(map);
      lineLayer = new L.FeatureGroup().addTo(map);

      getCoordinate();

      drawLegend();
    });
  </script>
</body>
</html>